package com.sise.netty.reactor模型.多Reactor模型;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
/**
 * @author idea
 * @data 2019/4/6
 */
public class NIOServer {

    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(1225));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //核心线程数目
        int coreNum = Runtime.getRuntime().availableProcessors();
        Processor[] processors = new Processor[coreNum];
        //创建处理器
        for (int i = 0; i < processors.length; i++) {
            processors[i] = new Processor();
        }
        int index = 0;
        //阻塞的
        while (selector.select() > 0) {
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator=keys.iterator();
           while(iterator.hasNext()){
               SelectionKey key=iterator.next();
               //如果此时客户端的连接还是保持accept状态，那就
               if(key.isAcceptable()){
                   ServerSocketChannel channel= (ServerSocketChannel) key.channel();
                   SocketChannel socketChannel=channel.accept();
                   socketChannel.configureBlocking(false);
                   System.out.println("接受信息成功！");
                   Processor processor = processors[(int) ((index++) / coreNum)];
                   processor.addChannel(socketChannel);
               }
               iterator.remove();

           }
        }
    }
}
